package com.ljc;


import com.ljc.dto.ListNode;

/**
 * @author clj
 * @date 2022/9/22
 * @desc Given the head of a sorted linked list,
 * delete all nodes that have duplicate numbers,
 * leaving only distinct numbers from the original list.
 * Return the linked list sorted as well.
 */
public class M82DeleteDuplicates {

    public static void main(String[] args) {
        ListNode head = new ListNode(1);
        head.next = new ListNode(2);
        head.next.next = new ListNode(2);
        head.next.next.next = new ListNode(2);
        head.next.next.next.next = new ListNode(2);
        head.next.next.next.next.next = new ListNode(3);

        ListNode cur = deleteDuplicates(head);
//        ListNode cur = head;
        while (cur != null) {
            System.out.println(cur.val);
            cur = cur.next;
        }

    }

    public static ListNode deleteDuplicates(ListNode head) {
        //特殊情况，头节点为null或头节点下一节点为null，直接返回头节点，这时不存在重复节点
        if (head == null || head.next == null) {
            return head;
        }
        if (head.val == head.next.val) {
            //如果头节点与，头节点的下一节点值相等，跳过所有相等节点。递归调用函数判断最后一个跳过节点的后一节点
            while (head != null && head.next != null && head.val == head.next.val) {
                head = head.next;
            }
            return deleteDuplicates(head.next);
        } else {
            //如果头节点与，头节点的下一节点值不等，递归调用函数判断头节点的后一节点.
            head.next = deleteDuplicates(head.next);
            return head;
        }
    }

    public static ListNode removeDuplicates(ListNode head) {
        //特殊情况，头节点为null或头节点下一节点为null，直接返回头节点，这时不存在重复节点
        if (head == null || head.next == null) {
            return head;
        }
        if (head.val == head.next.val) {
            if (head != null && head.next != null && head.val == head.next.val) {
                head = head.next;
            }
            return removeDuplicates(head);
        }else {
            head.next = removeDuplicates(head.next);
            return head;
        }
    }


}
